package com.sip.stream.gbstack;

import android.net.TrafficStats;
import android.os.HandlerThread;
import android.os.Process;
import android.util.Log;
import aria.apache.commons.net.ftp.FTPReply;

import com.gosuncn.gbstack.JniGS28181Agent;
import com.sip.stream.gbstack.Model.GSSendFrame;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class SendHelper {
    private static final String TAG = "SendHelper";

    protected static final int SEND_VIDEO_STOP_COUNT = 60;
    private HandlerThread backgroundThread;
    private SendHelperListener listener;
    private String mobileNetworkStr;
    private CompositeDisposable sendCompositeDisposable;
    private HandlerThread sendJniThread;
    private Thread sendThread;
    private BlockingDeque<GSSendFrame> waitDeque = new LinkedBlockingDeque(30);
    private AtomicBoolean isStarted = new AtomicBoolean(false);
    private AtomicBoolean sendVideoFlowOverMode = new AtomicBoolean();
    private AtomicBoolean sendKeyFailed = new AtomicBoolean();
    private AtomicBoolean modeChangeLock = new AtomicBoolean();
    private int sendVideoFlowOver = 0;
    private int sendVideoErrorCounter = 0;
    private long lastUidTxBytes = 0;
    private long maxLastUidTxBytesDes = 0;
    private int uidTxBytesCounter = 5;
    private long sepUidTxBytes = 0;
    private int wifiSignalLevel = -1;
    private boolean badNetWork = false;

    public interface SendHelperListener {
        void forceStop();
        void setRemotePerformanceLevel(int i);
    }

    static int access$410(SendHelper sendHelper) {
        int i = sendHelper.uidTxBytesCounter;
        sendHelper.uidTxBytesCounter = i - 1;
        return i;
    }

    public SendHelper(SendHelperListener sendHelperListener) {
        this.listener = sendHelperListener;
    }

    public void addFrame(GSSendFrame gSSendFrame) {
        this.waitDeque.offer(gSSendFrame);
    }

    public synchronized void addFrame(ByteBuffer byteBuffer, int i, long j) {
        if (byteBuffer != null) {
            if (byteBuffer.remaining() >= 1 && this.isStarted.get()) {
                if (!this.waitDeque.offer(new GSSendFrame(byteBuffer, i, j))) {
                    Log.w(TAG, "waitDeque full");
                }
            }
        }
    }

    public void startSend() {
        this.sendVideoFlowOver = 0;
        this.sendVideoErrorCounter = 0;
        this.maxLastUidTxBytesDes = 0L;
        this.sepUidTxBytes = 0L;
        this.uidTxBytesCounter = 5;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                SendHelper.this.m157lambda$startSend$0$comgosuncngbstackSendHelper();
            }
        };
        this.sendThread = new Thread(runnable, TAG);
        this.sendCompositeDisposable = new CompositeDisposable();
        Log.i(TAG, "startSend");
        Single.just(Boolean.TRUE).delay(5L, TimeUnit.SECONDS).subscribe(new SingleObserver<Boolean>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSuccess(Boolean bool) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                SendHelper.this.sendCompositeDisposable.add(disposable);
            }
        });
        this.sendThread.start();
    }

    public void m157lambda$startSend$0$comgosuncngbstackSendHelper() {
        this.isStarted.set(true);
        while (!this.sendThread.isInterrupted()) {
            GSSendFrame peek = this.waitDeque.peek();
            if (peek != null) {
                postInputVideoStream(peek);
            }
        }
        Log.i(TAG, "sendThread interrupted");
        this.isStarted.set(false);
    }

    public void release() {
        Log.i(TAG, "release");
        this.isStarted.set(false);
        this.sendThread.interrupt();
        this.waitDeque.clear();
        CompositeDisposable compositeDisposable = this.sendCompositeDisposable;
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
            this.sendCompositeDisposable = null;
        }
    }

    private void postInputVideoStream(GSSendFrame gSSendFrame) {
        ByteBuffer byteBuffer = gSSendFrame.byteBuffer;
        int i = gSSendFrame.frameType;
        long j = gSSendFrame.timestamp;
        if (i != 1 && this.sendKeyFailed.get()) {
            Log.i(TAG, "not send cause sendKeyFailed");
            try {
                this.waitDeque.pop();
                return;
            } catch (Exception e) {
                Log.w(TAG, "pop " + e.getMessage());
                return;
            }
        }
        int inputVideoStream = JniGS28181Agent.getInstance().inputVideoStream(byteBuffer, i, j);
        if (inputVideoStream == 10000) {
            try {
                this.waitDeque.pop();
            } catch (Exception e2) {
                Log.w(TAG, "pop " + e2.getMessage());
            }
            if (i == 1) {
                this.sendKeyFailed.set(false);
            }
            this.sendVideoErrorCounter = 0;
            if (this.sendVideoFlowOverMode.get()) {
                int i2 = this.sendVideoFlowOver;
                if (i2 < 0) {
                    Log.i(TAG, "sendVideoFlowOver < 0");
                    if (this.badNetWork) {
                        Log.i(TAG, "still badNetWork");
                        this.sendVideoFlowOver += 150;
                        return;
                    }
                    setRemotePerformanceLevel(0);
                    this.sendVideoFlowOverMode.set(false);
                    lockModeChangeLock();
                    return;
                }
                this.sendVideoFlowOver = i2 - 1;
            }
        } else if (inputVideoStream != 10000) {
            Log.i(TAG, "inputVideoStream failed " + inputVideoStream);
            if (i == 1) {
                this.sendKeyFailed.set(true);
                Log.i(TAG, "sendKeyFailed set true");
            }
            if (inputVideoStream == 10010) {
                if (!this.sendVideoFlowOverMode.get()) {
                    setSendVideoFlowOverMode();
                    return;
                } else if (!gSSendFrame.canRetry()) {
                    try {
                        this.waitDeque.pop();
                        return;
                    } catch (Exception e3) {
                        Log.w(TAG, "pop " + e3.getMessage());
                        return;
                    }
                } else {
                    Log.w(TAG, "sleep 100 retry");
                    return;
                }
            }
            Log.e(TAG, "forceStopRTP video");
            int i3 = this.sendVideoErrorCounter + 1;
            this.sendVideoErrorCounter = i3;
            if (i3 > 60) {
                forceStop();
            }
            try {
                this.waitDeque.pop();
            } catch (Exception e4) {
                Log.w(TAG, "pop " + e4.getMessage());
            }
        }
    }

    private synchronized void lockModeChangeLock() {
        this.modeChangeLock.set(true);
        Single.timer(5L, TimeUnit.SECONDS).subscribe(new SingleObserver<Long>() {
            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onSuccess(Long l) {
                SendHelper.this.modeChangeLock.set(false);
            }
        });
    }

    public synchronized void setSendVideoFlowOverMode() {
        lockModeChangeLock();
        this.sendVideoFlowOverMode.set(true);
        setRemotePerformanceLevel(1);
        this.waitDeque.clear();
        this.sendVideoFlowOver = FTPReply.FILE_ACTION_NOT_TAKEN;
    }

    public void setRemotePerformanceLevel(int i) {
        SendHelperListener sendHelperListener = this.listener;
        if (sendHelperListener != null) {
            sendHelperListener.setRemotePerformanceLevel(i);
        }
    }

    public void forceStop() {
        release();
        SendHelperListener sendHelperListener = this.listener;
        if (sendHelperListener != null) {
            sendHelperListener.forceStop();
        }
    }

    public void startCheck() {
        Log.i(TAG, "startCheck");
        Observable.interval(1L, TimeUnit.SECONDS).subscribeOn(getBackgroundScheduler()).doOnNext(new Consumer<Long>() {
            @Override
            public void accept(Long l) throws Exception {
                if (SendHelper.this.modeChangeLock.get()) {
                    return;
                }
                long uidTxBytes = TrafficStats.getUidTxBytes(Process.myUid());
                if (SendHelper.this.lastUidTxBytes > 0) {
                    long j = uidTxBytes - SendHelper.this.lastUidTxBytes;
                    if (SendHelper.this.sendVideoFlowOverMode.get()) {
                        return;
                    }
                    if (SendHelper.this.uidTxBytesCounter > 0) {
                        if (j > SendHelper.this.maxLastUidTxBytesDes) {
                            SendHelper.this.maxLastUidTxBytesDes = j;
                            SendHelper sendHelper = SendHelper.this;
                            sendHelper.sepUidTxBytes = (long) (((float) sendHelper.maxLastUidTxBytesDes) * 0.6f);
                            Log.i(SendHelper.TAG, "maxLastUidTxBytesDes " + SendHelper.this.maxLastUidTxBytesDes + " sepUidTxBytes " + SendHelper.this.sepUidTxBytes);
                        }
                        SendHelper.access$410(SendHelper.this);
                    } else if (j < SendHelper.this.sepUidTxBytes) {
                        Log.w(SendHelper.TAG, "UidTxBytes setSendVideoFlowOverMode");
                        SendHelper.this.setSendVideoFlowOverMode();
                    }
                }
                SendHelper.this.lastUidTxBytes = uidTxBytes;
            }
        }).subscribe(new Observer<Long>() {
            @Override
            public void onComplete() {
            }

            @Override
            public void onNext(Long l) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                if (SendHelper.this.sendCompositeDisposable != null) {
                    SendHelper.this.sendCompositeDisposable.add(disposable);
                }
            }

            @Override
            public void onError(Throwable th) {
                th.printStackTrace();
            }
        });
    }

    private Scheduler getSendBackgroundScheduler() {
        if (this.sendJniThread == null) {
            HandlerThread handlerThread = new HandlerThread(TAG);
            this.sendJniThread = handlerThread;
            handlerThread.start();
        }
        return AndroidSchedulers.from(this.sendJniThread.getLooper());
    }

    private Scheduler getBackgroundScheduler() {
        if (this.backgroundThread == null) {
            HandlerThread handlerThread = new HandlerThread(TAG);
            this.backgroundThread = handlerThread;
            handlerThread.start();
        }
        return AndroidSchedulers.from(this.backgroundThread.getLooper());
    }

    public void setNetStatus(String mobileNetworkStr, int wifiSignalLevel) {
        if (wifiSignalLevel >= 0) {
            int i2 = this.wifiSignalLevel;
            if (i2 >= 0 && wifiSignalLevel >= 0) {
                if (wifiSignalLevel > i2) {
                    this.badNetWork = false;
                    this.sendVideoFlowOver = 15;
                    Log.i(TAG, " badNetWork = false");
                }
                if (wifiSignalLevel < 2) {
                    Log.i(TAG, " badNetWork = true");
                    this.badNetWork = true;
                }
            }
        } else {
            String str2 = this.mobileNetworkStr;
            if (str2 != null && mobileNetworkStr != null && !str2.equalsIgnoreCase("newMobileNetworkStr")) {
                Log.i(TAG, "mobileNetworkStr " + this.mobileNetworkStr + "  newMobileNetworkStr " + mobileNetworkStr);
                if (this.mobileNetworkStr.equalsIgnoreCase("4G") && mobileNetworkStr.equalsIgnoreCase("5G")) {
                    Log.i(TAG, " badNetWork = false");
                    this.badNetWork = false;
                    this.sendVideoFlowOver = 15;
                }
                if (this.mobileNetworkStr.equalsIgnoreCase("5G") && mobileNetworkStr.equalsIgnoreCase("4G")) {
                    Log.i(TAG, " badNetWork = true");
                    this.badNetWork = true;
                }
            }
        }
        this.mobileNetworkStr = mobileNetworkStr;
        this.wifiSignalLevel = wifiSignalLevel;
    }
}
